//
//  HistoryCarStyleVC.m
//  zhiche--delivery
//
//  Created by LeeBruce on 16/6/13.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "HistoryCarStyleVC.h"
#import "Common.h"
#import "TopBackView.h"
#import <Masonry.h>
@interface HistoryCarStyleVC ()<UITableViewDelegate,UITableViewDataSource>
{
    Common * com;
    UIView * backview;
}
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UITableView *tableVIew;
@property (nonatomic,strong) UITableView *leftTableView;
@property (nonatomic,strong) UITableView *rightTableView;
@property (nonatomic,strong) UITableView * SearchTable;
@property (nonatomic,strong) NSMutableArray * searchArr;
//@property (nonatomic,strong) NSMutableDictionary *dataDictionary;
@property (nonatomic,strong) NSMutableArray *leftDataArray;
@property (nonatomic,strong) NSMutableArray *rightDataArray;
@property (nonatomic,strong) NSMutableArray *dataArray;

@property (nonatomic,strong) NSMutableArray *leftSectionArray;

@property (nonatomic,copy) NSString *carBrandString;
@property (nonatomic,copy) NSString *carBrandID;
@property (nonatomic,copy) NSString *carTypeID;
@property (nonatomic,copy) NSString *careTypeString;
@property (nonatomic,copy) NSString *logoString;

@end

@implementation HistoryCarStyleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    com = [[Common alloc]init];
    self.leftDataArray = [NSMutableArray array];
    self.rightDataArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    self.leftSectionArray = [NSMutableArray array];
    self.searchArr = [[NSMutableArray alloc]init];
//    self.searchArr = @[@"奥迪",@"宝马",@"奔驰"].mutableCopy;
    self.view.backgroundColor = GrayColor;
    TopBackView *topBackView= [[TopBackView alloc]initViewWithFrame:CGRectMake(0, 0, screenWidth, 64) andTitle:@"选择车型"];
    
    [topBackView.leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    
    topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:topBackView];
    
    [self initDataSouces];
    
    [self initTableView];


}


-(void)viewWillAppear:(BOOL)animated{
    
    UIButton * btn1 = (UIButton*)[self.view viewWithTag:100];
    UIButton * btn2 = (UIButton*)[self.view viewWithTag:200];
    [btn1 setTitleColor:YellowColor forState:UIControlStateNormal];
    [btn2 setTitleColor:BlackColor forState:UIControlStateNormal];

}
-(void)initTableView
{
    //常用车型
    UIButton *useButton = [UIButton buttonWithType:UIButtonTypeCustom];
    useButton.frame = CGRectMake(0, 64, screenWidth/2, cellHeight);
    [useButton setTitle:@"常用车型" forState:UIControlStateNormal];
    [useButton setTitleColor:YellowColor forState:UIControlStateNormal];
    useButton.tag = 100;
    useButton.backgroundColor = WhiteColor;
    useButton.titleLabel.font = Font(14);
    [self.view addSubview:useButton];
    [useButton addTarget:self action:@selector(userButtonAction) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(useButton.frame), 64, 0.5, cellHeight)];
    label.backgroundColor = LineGrayColor;
    [self.view addSubview:label];
    [self.view addSubview:label];
    
    //全部车型
    
    UIButton *allButton = [UIButton buttonWithType:UIButtonTypeCustom];
    allButton.frame = CGRectMake( CGRectGetMaxX(label.frame), 64, screenWidth/2, cellHeight);
    [allButton setTitle:@"全部车型" forState:UIControlStateNormal];
    allButton.tag = 200;
    allButton.backgroundColor = WhiteColor;
    [allButton setTitleColor:BlackColor forState:UIControlStateNormal];
    allButton.titleLabel.font = Font(14);
    [self.view addSubview:allButton];
    [allButton addTarget:self action:@selector(allButtonAction) forControlEvents:UIControlEventTouchUpInside];

    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(allButton.frame), screenWidth, 10)];
    view.backgroundColor = GrayColor;
    [self.view addSubview:view];
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(useButton.frame) + 10, screenWidth, screenHeight - CGRectGetMaxY(useButton.frame))];
    [self.view addSubview:self.scrollView];
    
    self.scrollView.backgroundColor = GrayColor;
    
    self.tableVIew = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - CGRectGetMaxY(useButton.frame)) style:UITableViewStyleGrouped];
    
    self.tableVIew.delegate = self;
    self.tableVIew.dataSource = self;
    self.tableVIew.tableFooterView = [[UIView alloc]init];
    [self.scrollView addSubview:self.tableVIew];
    
    UITextField * field = [self createField:@"按照车型名称/首字母/全拼音搜索" andFont:FontOfSize14];
    field.tag = 111111;
    [self.scrollView addSubview:field];
    [field mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView.mas_left).with.offset(Main_Width+18*kWidth);
        make.top.mas_equalTo(self.scrollView.mas_top);
        make.size.mas_equalTo(CGSizeMake(Main_Width-36*kWidth, 30*kHeight));
    }];
    
    self.leftTableView = [[UITableView alloc]initWithFrame:CGRectMake(screenWidth, 50, Main_Width-2, screenHeight - 150*kHeight) style:UITableViewStylePlain];
    self.leftTableView.delegate = self;
    self.leftTableView.dataSource = self;
    self.leftTableView.showsHorizontalScrollIndicator = NO;
    self.leftTableView.showsVerticalScrollIndicator = NO;
    self.leftTableView.tableFooterView = [[UIView alloc]init];
    [self.scrollView addSubview:self.leftTableView];
//    self.leftTableView.sectionIndexColor = BlackColor;
    self.leftTableView.sectionIndexBackgroundColor= GrayColor;
//    self.leftTableView.sectionIndexTrackingBackgroundColor= RedColor;
//
    UIImageView *imageV = [[UIImageView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(self.leftTableView.frame) + 16, 0, 0.5,  screenHeight - 104*kHeight)];
    imageV.image = [UIImage imageNamed:@"project_shaixuan_left_line1"];
    
    [self.scrollView addSubview:imageV];
    
    
    self.rightTableView = [[UITableView alloc]initWithFrame:CGRectMake(screenWidth+screenWidth/2.0 - 16, 50, screenWidth/2.0 , screenHeight - 150*kHeight) style:UITableViewStylePlain];
    self.rightTableView.delegate = self;
    self.rightTableView.dataSource = self;
    self.rightTableView.tableFooterView = [[UIView alloc]init];
    [self.scrollView addSubview:self.rightTableView];

    
    backview = [[UIView alloc]init];
    backview.backgroundColor = [UIColor whiteColor];
    backview.hidden = YES;

    [self.scrollView addSubview:backview];
    [backview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.scrollView.mas_left).with.offset(Main_Width);
        make.top.mas_equalTo(field.mas_bottom).with.offset(8*kHeight);
        make.size.mas_equalTo(CGSizeMake(Main_Width, Main_height-field.frame.origin.y-field.frame.size.height-8*kHeight));
    }];
    
    
    _SearchTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 64*kHeight, Main_Width, 86*kHeight) style:UITableViewStylePlain];
    [_SearchTable setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _SearchTable.delegate = self;
    _SearchTable.dataSource = self;
    [backview addSubview:_SearchTable];
    [_SearchTable mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backview.mas_left);
        make.top.mas_equalTo(backview.mas_top);
        make.size.mas_equalTo(CGSizeMake(Main_Width,backview.frame.size.height-86*kHeight));
    }];
    [_SearchTable reloadData];
    
}

-(void)userButtonAction
{
  
    UIButton * btn1 = (UIButton *)[self.view viewWithTag:100];
    UIButton * btn2 = (UIButton *)[self.view viewWithTag:200];
    [btn1 setTitleColor:YellowColor forState:UIControlStateNormal];
    [btn2 setTitleColor:BlackColor forState:UIControlStateNormal];

//    UIButton * allButton = (UIButton*)[self.view viewWithTag:200];
//    allButton setTitleColor:<#(nullable UIColor *)#> forState:<#(UIControlState)#>
    CGPoint offestPoint = CGPointMake(0, 0);
    [self.scrollView setContentOffset:offestPoint];
    
    [self initDataSouces];
    
    
    
    
}
-(UITextField*)createField:(NSString*)placeholder andFont:(double)font{
    
    UITextField * field =[[UITextField alloc]init];
    field.frame = CGRectMake(0, 0, Main_Width-91, 50);
    field.delegate = self;
    field.userInteractionEnabled = YES;
    field.textAlignment = NSTextAlignmentLeft;
    field.keyboardType = UIKeyboardTypeDefault;
    field.backgroundColor = WhiteColor;
    field.layer.cornerRadius = 5;
    field.layer.borderWidth = 0.5;
    field.layer.borderColor = WhiteColor.CGColor;
    
    // 为了给textField添加一个图片，创建一个imageView
    UIImageView *accLeftView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_search"]];
    accLeftView.frame = CGRectMake(20, 5, 24, 13);
    //    accLeftView.contentMode = UIViewContentModeLeft;
    // 添加到左侧视图中
    field.leftView = accLeftView;
    field.leftViewMode = UITextFieldViewModeAlways; // 这句一定要加，否则不显示
    
    field.placeholder =placeholder;
    [field setFont:[UIFont fontWithName:@"STHeitiSC" size:font]];
    [field addTarget:self action:@selector(textFieldWithText:) forControlEvents:UIControlEventEditingChanged];
    [field addTarget:self action:@selector(textFieldWithText1:) forControlEvents:UIControlEventEditingDidBegin];
    [field placeholderRectForBounds:CGRectMake(100.0, 100.0, 100, 100)];
    
    
    return field;
}

-(void)textFieldWithText1:(UITextField*)field{
    
    [self.SearchTable mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(backview.frame.size.height-300*kHeight);
    }];
    
}


-(void)textFieldWithText:(UITextField*)field{
    
    
    NSString * name1 = field.text;
    
    NSString *strUrl = [name1 stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (field.text.length>0) {
        
        NSString * url = [NSString stringWithFormat:@"%@?keystr=%@",vehicle_search_Url,strUrl];
        
        //url汉字转码
        NSString *str1 = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

        [Common requestWithUrlString:str1 contentType:application_json finished:^(id responseObj) {
            
            
            NSArray * arr = responseObj[@"data"];
            if (arr.count>0) {
                _searchArr = [NSMutableArray arrayWithArray:responseObj[@"data"]];
            }else{
                [_searchArr removeAllObjects];
            }

            backview.hidden = NO;
            [self.SearchTable reloadData];
            
        } failed:^(NSString *errorMsg) {
            NSLog(@"%@",errorMsg);
        }];
    }
    
    else{
        UITextField * field = (UITextField*)[self.scrollView viewWithTag:11111];
        [field resignFirstResponder];
        [self.searchArr removeAllObjects];
        backview.hidden = YES;
        [self.SearchTable reloadData];
    }


}





-(void)allButtonAction
{
    
    UIButton * btn1 = (UIButton *)[self.view viewWithTag:100];
    UIButton * btn2 = (UIButton *)[self.view viewWithTag:200];
    [btn2 setTitleColor:YellowColor forState:UIControlStateNormal];
    [btn1 setTitleColor:BlackColor forState:UIControlStateNormal];


    CGPoint offestPoint = CGPointMake(screenWidth, 0);
    
    [self.scrollView setContentOffset:offestPoint];
    
    [self initLeftDataSource];
    
    
    
}


-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return tableView == self.leftTableView ? _leftSectionArray.count:1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (tableView == self.tableVIew) {
        return self.dataArray.count;
    } else if (tableView == self.leftTableView) {
        return [self.leftDataArray[section] count];
    } else if(tableView == self.rightTableView){
        return self.rightDataArray.count;
    }else{
        return self.searchArr.count;
    }
    
//    if (tableView == self.leftTableView) {
//        
//        return (self.leftDataArray.count > 0) ? self.leftDataArray.count : 0;
//    } else {
//        return  (self.rightDataArray.count > 0) ? self.rightDataArray.count : 0;
//    }
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableVIew) {
        
        
        NSString *cellString = @"userSting";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
        }
        NSString * string= @"";
        if ([_dataArray  count]>0) {
            string = [NSString stringWithFormat:@"%@-%@",_dataArray[indexPath.row][@"brandName"],_dataArray[indexPath.row][@"vehicleName"]];
        }
        cell.textLabel.text = string;
        cell.textLabel.font = Font(14);
        return cell;
        
    } else  if (tableView == self.leftTableView) {
        
        NSString *cellString = @"cartypeString";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
        }
        
        if (indexPath.row == 0) {
            cell.selected = YES;
        }
        
        if (self.leftDataArray.count > 0) {
            NSString * string = [NSString stringWithFormat:@"%@",self.leftDataArray[indexPath.section][indexPath.row][@"brandName"]];
            cell.textLabel.text = string;
            
        }
        cell.textLabel.font = Font(14);
        
        
        for(UIView *view in [tableView subviews]){
          
            if([[[view class] description] isEqualToString:@"UITableViewIndex"])
            {
                [view setBackgroundColor:[UIColor redColor]];
            }
        }
        
        //默认选中第一行
        if (self.leftDataArray.count > 0) {
            
            if (indexPath.section == 0) {
                
                [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
                [self tableView:self.leftTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
            }
        }
        
        
        
        return cell;
    } else if(tableView == self.rightTableView){
        
        
        NSString *cellString = @"cartypeString1";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
        }
        
        if (self.rightDataArray.count > 0) {
            cell.textLabel.text = self.rightDataArray[indexPath.row][@"vehicleName"];
            
            
            
        }
        cell.textLabel.font = Font(14);
//        if (indexPath.row == 0) {
//            cell.backgroundColor = GrayColor;
//        }
        //默认选中第一行
//        [self tableView:self.rightTableView didSelectRowAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
//        
        return cell;
    }else{
        
        NSString *cellString = @"search";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellString];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellString];
        }
        
        

        if (self.searchArr.count > 0) {
            cell.textLabel.text = self.searchArr[indexPath.row][@"bvName"];
            
        }
        
        UIView * viewline = [[UIView alloc]init];
        viewline.backgroundColor = LineGrayColor;
        [cell.contentView addSubview:viewline];
        [viewline mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(cell.contentView.mas_bottom);
            make.left.mas_equalTo(cell.contentView.mas_left);
            make.size.mas_equalTo(CGSizeMake(Main_Width, 0.5));
        }];

        
        cell.textLabel.font = Font(14);

        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if (tableView == self.tableVIew) {
//        self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];

        if (self.dataArray.count > 0) {
            NSString * vehicleName = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"vehicleName"]];
            NSString * carBrandString = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"brandName"]];
            NSString * carBrandID = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"brandId"]];
            NSString * vehicleId = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"vehicleId"]];

            NSString * brandLogo = [NSString stringWithFormat:@"%@",self.dataArray[indexPath.row][@"brandLogo"]];
//            NSLog(@"%@",self.dataArray[indexPath.row]);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

            self.callBack(carBrandID,vehicleId,carBrandString,vehicleName,brandLogo);
            [self.navigationController popViewControllerAnimated:YES];
            });
        }

        
        
    }else if (tableView == self.SearchTable){
        
        //        {
        //            brandLogo = "http://qiniu.logo.huiyunche.cn/Audi.png?e=1474531443&token=wQknukoe-lwcjLKEnsBz-BrL61M1BEMP0Gq_M2qP:iKuWTD-vL3f9TLW_pit4-ju-J6k=";
        //            brandName = "\U5965\U8fea";
        //            bvName = "\U5965\U8fea-\U5965\U8fea100";
        //            id = 3;
        //            vehicleId = 11;
        //            vehicleName = "\U5965\U8fea100";
        //        },
        NSLog(@"search");
        if (_searchArr.count > 0) {
            NSString * vehicleName = [NSString stringWithFormat:@"%@",self.searchArr[indexPath.row][@"vehicleName"]];
            NSString * carBrandString = [NSString stringWithFormat:@"%@",self.searchArr[indexPath.row][@"brandName"]];
            NSString * carBrandID = [NSString stringWithFormat:@"%@",self.searchArr[indexPath.row][@"id"]];
            NSString * vehicleId = [NSString stringWithFormat:@"%@",self.searchArr[indexPath.row][@"vehicleId"]];
            
            NSString * brandLogo = [NSString stringWithFormat:@"%@",self.searchArr[indexPath.row][@"brandLogo"]];
            //            NSLog(@"%@",self.dataArray[indexPath.row]);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                self.callBack(carBrandID,vehicleId,carBrandString,vehicleName,brandLogo);
                [self.navigationController popViewControllerAnimated:YES];
            });
        }
    }else{
        
        if (tableView == self.leftTableView) {
            
            if (self.leftDataArray.count > 0) {
                
                NSLog(@"%@",self.leftDataArray);
                self.carBrandString = _leftDataArray[indexPath.section][indexPath.row][@"brandName"];//车系
                self.logoString = self.leftDataArray[indexPath.section][indexPath.row][@"brandLogo"];//车系logo
                self.carBrandID = self.leftDataArray[indexPath.section][indexPath.row][@"id"];//车系id
                
                [self initRightDataWith:self.leftDataArray[indexPath.section][indexPath.row][@"id"]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                [self.rightTableView reloadData];
                
            });
            
        } else {
            
            _careTypeString = self.rightDataArray[indexPath.row][@"vehicleName"];//车型
//            NSString *brandString = [self.carBrandString stringByAppendingString:self.careTypeString];//车系＋车型
            NSString *brandString = self.carBrandString;

            self.carTypeID = _rightDataArray[indexPath.row][@"id"];//车型id
            NSString * brandLogo = self.logoString;
            //延迟执行
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if (self.callBack) {
                    
                    /*
                     str  车系＋车型
                     str1 类别（SUV 或者商务）
                     str2 长宽高
                     str3 车系logo
                     
                     */
                    self.callBack(self.carBrandID,self.carTypeID,brandString,_careTypeString,brandLogo);
                    
                }
                //            if (self.carTypeID) {
                //                /*
                //                 str  车系ID
                //                 str1 车型ID
                //                 str2 车系名称
                //                 str3 品牌名称
                //
                //                 */
                //
                //                self.callBackId(self.carBrandID,self.carTypeID,self.carBrandString,self.careTypeString);
                //                
                //            }
                
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }

    }
   }

-(void)initDataSouces
{
    [Common requestWithUrlString:user_vehicle_list contentType:application_json finished:^(id responseObj) {
        
        if (self.dataArray.count > 0) {
            [self.dataArray removeAllObjects];
        }
        
        self.dataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        if (self.dataArray.count > 0) {
            [self.tableVIew reloadData];
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];

}


-(void)initLeftDataSource
{
    
    //    NSString *urlString = [NSString stringWithFormat:@"%@brand/list",Main_interface];
    
    [Common requestWithUrlString:brand_list contentType:application_json finished:^(id responseObj) {
        
        
        if (self.leftDataArray.count > 0) {
            [self.leftDataArray removeAllObjects];
        }
        
        
        self.leftDataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        if (self.leftDataArray.count > 0) {
            
            
            NSMutableArray * leftArr = [[NSMutableArray alloc]init];
            
            for (int i=0; i<[responseObj[@"data"] count]; i++) {
                [leftArr addObject:responseObj[@"data"][i][@"brandPrefix"]];
            }

            NSArray * array = [NSArray arrayWithArray:leftArr];
            
            NSMutableDictionary *dict = [NSMutableDictionary dictionary];
            
            for (NSNumber *number in array) {
                [dict setObject:number forKey:number];
            }
            
            array = [dict allKeys];
            NSArray * array1 = [[NSArray alloc]init];
            array1 = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
                return [obj1 compare:obj2 options:NSNumericSearch];
            }];
            
            //section 字母排序
            _leftSectionArray = (NSMutableArray*)array1;
            
            [_leftDataArray removeAllObjects];
            for (int j=0; j<_leftSectionArray.count; j++) {
                
                NSMutableArray * arr = [[NSMutableArray alloc]init];
                
                for (int i=0; i<[responseObj[@"data"] count]; i++) {
                    
                NSString * new = responseObj[@"data"][i][@"brandPrefix"];

                    if ([new isEqualToString:_leftSectionArray[j]]) {
                        [arr addObject:responseObj[@"data"][i]];
                    }
                }
                [_leftDataArray addObject:arr];
            }
            
            [self.leftTableView reloadData];
            [self initRightDataWith:self.leftDataArray[0][0][@"id"]];
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
    
}

-(void)initRightDataWith:(NSString *)string
{

    NSString * url = [NSString stringWithFormat:@"%@?brandid=%@",vehicle_list,string];
    [Common requestWithUrlString:url contentType:application_json finished:^(id responseObj) {
        if (self.rightDataArray.count > 0) {
            [self.rightDataArray removeAllObjects];
        }
        self.rightDataArray = [NSMutableArray arrayWithArray:responseObj[@"data"]];
        
        if (self.rightDataArray.count > 0) {
            [self.rightTableView reloadData];
        }
        
    } failed:^(NSString *errorMsg) {
        NSLog(@"%@",errorMsg);
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return cellHeight;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
//    return 0.001;
    return tableView == self.leftTableView ? 43*kHeight:0.001;
}

//-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
//    
//    
//    if (tableView == self.leftTableView) {
//        
//        return _leftSectionArray[section];
//    }
//    return nil;
//}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    if (_leftSectionArray.count>0&&tableView == _leftTableView) {
        UIView *view = [[UIView alloc]init];
        view.backgroundColor = sectionHeadView;
        view.frame = CGRectMake(0, 0, Main_Width, 43*kHeight);
        
        UILabel * label = [com createUIlabel:_leftSectionArray[section] andFont:FontOfSize14 andColor:BlackColor];
        [view addSubview:label];
        [label mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view.mas_left).with.offset(18*kWidth);
            make.centerY.equalTo(view.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(Main_Width/2, 43*kHeight));
        }];
        
        return view;
    }else{
        return nil;
    }
    
}




//表格的自动搜索功能
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    
    if (tableView == self.leftTableView) {
        NSMutableArray * arr = [[NSMutableArray alloc]init];
        //添加所有分区的名称
        //通过分区名称进行模糊查询
        for (int i = 0; i<_leftSectionArray.count; i++) {
            [arr addObject:[NSString stringWithFormat:@"%@",_leftSectionArray[i]]];
        }
        return arr;
    }
    return nil;
}


//点击return按钮 键盘隐藏 这是协议中的方法
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self.SearchTable mas_updateConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(backview.frame.size.height-86*kHeight);
    }];

    //键盘隐藏 也就是让键盘取消第一响应者身份
    [textField resignFirstResponder];
    return YES;
}





-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
